package com.nus.application.web.user;

import com.nus.application.ejb.user.UserEjbLocal;
import com.nus.application.web.base.BaseAction;
import com.nus.application.web.user.form.UserLoginForm;
import com.nus.constant.ConstantSystemParam;
import com.nus.dataaccess.dao.user.UserAccount;
import com.opensymphony.xwork2.ValidationAware;
import javax.inject.Inject;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author kenny
 */
public class UserLogin extends BaseAction implements ValidationAware {

    @Inject
    UserEjbLocal userEjb;

    public String doLogin() {
        System.err.println(this.getForm().getUserAccount().getUsername());
        System.err.println(this.getForm().getUserAccount().getPassword());
        
        UserAccount userAccount = userEjb.doLogin(this.getForm().getUserAccount().getUsername(), this.getForm().getUserAccount().getPassword());
        if(userAccount == null){
            super.addActionError(super.getText("error.invalid_username_or_password"));
            return INPUT;
        }else{
            this.session.put(ConstantSystemParam.SESSION, userAccount);
        }
        return SUCCESS;
    }
    
    public String doLogout(){
        this.session.put(ConstantSystemParam.SESSION, null);
        return SUCCESS;
    
    }
    
    private UserLoginForm form = new UserLoginForm();
    public UserLoginForm getForm() {return form;}
    public void setForm(UserLoginForm form) {this.form = form;}

    @Override
    public void validate() {
        System.out.print("hello here");
        if(!super.isSaveEvent()){
            super.clearActionErrors();
            return;
        }
        
        System.out.print("validating");
        
        System.out.print(this.getForm().getUserAccount().getUsername());
        System.out.print(this.getForm().getUserAccount().getPassword());
        
        if(StringUtils.isEmpty(this.getForm().getUserAccount().getUsername()))
            super.addActionError(super.getText("error.username_is_required"));
        
        if(StringUtils.isEmpty(this.getForm().getUserAccount().getPassword()))
            super.addActionError(super.getText("error.password_is_required"));
        
        /*
        UserAccount userAccount = userEjb.retrieveUserByUsername(this.getForm().getUserAccount().getUsername());
        if (userAccount == null || userAccount.getPassword() != this.getForm().getUserAccount().getPassword()) {
            super.addActionError(super.getText("error.login_is_incorrect"));
        }

        if (!super.hasActionErrors()) {
            // set login here
        }
        */
    }
}
